package org.jeecg.modules.xl.h5api.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.kuaidi100.sdk.api.QueryTrack;
import com.kuaidi100.sdk.core.IBaseClient;
import com.kuaidi100.sdk.pojo.HttpResult;
import com.kuaidi100.sdk.request.QueryTrackParam;
import com.kuaidi100.sdk.request.QueryTrackReq;
import com.kuaidi100.sdk.response.QueryTrackData;
import com.kuaidi100.sdk.response.QueryTrackResp;
import com.kuaidi100.sdk.utils.SignUtils;
import dm.jdbc.d.U;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.xl.aftersale.entity.XlCustomerAftersale;
import org.jeecg.modules.xl.aftersale.entity.XlCustomerAftersaleDetail;
import org.jeecg.modules.xl.aftersale.mapper.XlCustomerAftersaleDetailMapper;
import org.jeecg.modules.xl.aftersale.mapper.XlCustomerAftersaleMapper;
import org.jeecg.modules.xl.common.XlLogUtil;
import org.jeecg.modules.xl.h5api.service.IH5APIService;
import org.jeecg.modules.xl.h5api.vo.*;
import org.jeecg.modules.xl.kuaidi100.entity.XlKuaidi100Logitrace;
import org.jeecg.modules.xl.kuaidi100.service.IXlKuaidi100LogitraceService;
import org.jeecg.modules.xl.logicmana.entity.XlCustomerLogisticPackage;
import org.jeecg.modules.xl.logicmana.mapper.XlCustomerLogisticPackageMapper;
import org.jeecg.modules.xl.logicmana.service.IXlCustomerLogisticPackageService;
import org.jeecg.modules.xl.order.dto.OrderDetailNew;
import org.jeecg.modules.xl.order.entity.XlCustomerOrde;
import org.jeecg.modules.xl.order.entity.XlCustomerOrderDetail;
import org.jeecg.modules.xl.order.service.IXlCustomerOrdeService;
import org.jeecg.modules.xl.order.service.IXlCustomerOrderDetailService;
import org.jeecg.modules.xl.order.utils.DictUtils;
import org.jeecg.modules.xl.order.utils.StrCommonUtil;
import org.jeecg.modules.xl.product.service.IXlProductInfoService;
import org.jeecg.modules.xl.shengfutong.config.ShengftConf;
import org.jeecg.modules.xl.shengfutong.request.OrderQueryRequest;
import org.jeecg.modules.xl.shengfutong.request.PayNotifyRequest;
import org.jeecg.modules.xl.shengfutong.response.QueryOrderResponse;
import org.jeecg.modules.xl.shengfutong.util.ShengFuTongSignUtil;
import org.jeecg.modules.xl.store.entity.XlCustomerMystore;
import org.jeecg.modules.xl.store.entity.XlCustomerStoreInfo;
import org.jeecg.modules.xl.store.service.IXlCustomerMystoreService;
import org.jeecg.modules.xl.store.service.IXlCustomerStoreInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author deco
 * @create 2024-11-21
 */
@Service
public class H5APIService implements IH5APIService {
    @Resource
    private XlCustomerLogisticPackageMapper xlCustomerLogisticPackageMapper;

    @Resource
    private XlCustomerAftersaleMapper xlCustomerAftersaleMapper;

    @Resource
    private IXlCustomerOrdeService xlCustomerOrdeService;

    @Resource
    private IXlCustomerOrderDetailService xlCustomerOrderDetailService;

    @Resource
    private XlCustomerAftersaleDetailMapper xlCustomerAftersaleDetailMapper;

    @Autowired
    private XlLogUtil xlLogUtil;
    @Resource
    private IXlProductInfoService xlProductInfoService;

    @Resource
    private IXlCustomerMystoreService xlCustomerMystoreService;

    @Autowired
    private DictUtils dictUtils;

    @Autowired
    private IXlCustomerStoreInfoService xlCustomerStoreInfoService;

    @Autowired
    private IXlCustomerLogisticPackageService xlCustomerLogisticPackageService;
    @Override
    public List<LogiOrderDetail> getLogiOrderDetail(String logiOrder) {
        return xlCustomerLogisticPackageMapper.queryilogiDetail(logiOrder);
    }

    @Override
    public void addAfterSaltOrder(AfterSaltOrderAddVo afterSaltOrderAddVo) {
        XlCustomerAftersale xlCustomerAftersale = new XlCustomerAftersale();
        BeanUtils.copyProperties(afterSaltOrderAddVo, xlCustomerAftersale);
        xlCustomerAftersale.setLogiCode(afterSaltOrderAddVo.getLogiOrder());
        String pre = "SHD"+new SimpleDateFormat("yyMMdd").format(new Date());	//编码前缀
        //流水号
        int maxNumber = StrCommonUtil.getStringNumber(xlCustomerAftersaleMapper.queryMaxCodeNumber(pre));

        xlCustomerAftersale.setWorkorder(pre + String.format("%03d", maxNumber+1));    //编号生成;
        xlCustomerAftersale.setWoStatus(dictUtils.getDictValue("audit_state","待审核"));//审核状态
        xlCustomerAftersale.setWoNote("");
        Double totalNum = 0.0;//售后商品总数量
        Integer detailNum = 0;//售后商品种数
        Double totalAmount = 0.0; //售后总金额
        QueryWrapper<XlCustomerOrde> ordeQueryWrapper = new QueryWrapper<>();
        ordeQueryWrapper.eq("order_code",afterSaltOrderAddVo.getOrderCode());
        XlCustomerOrde xlCustomerOrdeTarget  = xlCustomerOrdeService.getOne(ordeQueryWrapper);

        QueryWrapper<XlCustomerOrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
        orderDetailQueryWrapper.eq("order_code",afterSaltOrderAddVo.getOrderCode());
        List<XlCustomerOrderDetail> orderDetailList  = xlCustomerOrderDetailService.list(orderDetailQueryWrapper);

        // 将 List 转换为 Map，key 是 upcCode，value 是 XlCustomerOrderDetail 对象
        Map<String, XlCustomerOrderDetail> orderDetailMap = orderDetailList.stream()
                .collect(Collectors.toMap(
                        XlCustomerOrderDetail::getUpcCode, // Key: upcCode
                        detail -> detail                   // Value: XlCustomerOrderDetail 对象本身
                ));

        xlCustomerAftersale.setStoreCode(xlCustomerOrdeTarget.getStoreCode());
        xlCustomerAftersale.setStoreName(xlCustomerOrdeTarget.getStoreName());
        List<AfterSaltOrderDetailAddVo> detailAddVos = afterSaltOrderAddVo.getAftersaleDetailList();
        for(AfterSaltOrderDetailAddVo detailAddVo : detailAddVos){
            XlCustomerAftersaleDetail po = new XlCustomerAftersaleDetail();
            po.setWorkorder(xlCustomerAftersale.getWorkorder());
            po.setOrderId(xlCustomerOrdeTarget.getId());
            po.setOrderCode(xlCustomerOrdeTarget.getOrderCode());
            XlCustomerOrderDetail xlCustomerOrderDetailTemp = orderDetailMap.get(detailAddVo.getUpcCode());
            //查询产品明细

            po.setProductId(xlCustomerOrderDetailTemp.getProductId());
            po.setUpcCode(xlCustomerOrderDetailTemp.getUpcCode());

            po.setProductPrice(xlCustomerOrderDetailTemp.getProductPrice());
            po.setAftersaleQuantity(detailAddVo.getAftersaleQuantity());
            po.setAftersaleAmount(po.getProductPrice().multiply(po.getAftersaleQuantity()));
            po.setReason(detailAddVo.getReason());
            po.setPackageNum(detailAddVo.getNum());//包裹数量
            if(ObjectUtil.isEmpty(detailAddVo.getReason())){
                po.setReason(xlCustomerAftersale.getRenson());
            }

            xlCustomerAftersaleDetailMapper.insert(po);

            totalNum = totalNum + po.getAftersaleQuantity().doubleValue();
            totalAmount = totalAmount + po.getAftersaleAmount().doubleValue();
            detailNum = detailNum + 1;
        }
        xlCustomerAftersale.setLogiCode(afterSaltOrderAddVo.getLogiOrder());
        xlCustomerAftersale.setTotalNum(totalNum);
        xlCustomerAftersale.setDetailNum(detailNum);
        xlCustomerAftersale.setTotalAmount(totalAmount);
        xlCustomerAftersaleMapper.insert(xlCustomerAftersale);
        xlLogUtil.insertLog(xlCustomerAftersale.getLogiCode(),"支付回调","支付成功回调通知",new Date(),"待支付","待审核");

    }

    @Override
    public List<AfterSaltOrderVO> getAfterOrderList(String storeCode, String woStatus) {
        QueryWrapper<XlCustomerAftersale> ordeQueryWrapper = new QueryWrapper<>();
        ordeQueryWrapper.eq("store_code",storeCode);
        ordeQueryWrapper.eq(!woStatus.equals("all"),"wo_status",woStatus);
        List<XlCustomerAftersale> list  = xlCustomerAftersaleMapper.selectList(ordeQueryWrapper);
        List<AfterSaltOrderVO> targetResult = new ArrayList();
        for(XlCustomerAftersale xlCustomerAftersale : list){
            AfterSaltOrderVO afterSaltOrderVO = new AfterSaltOrderVO();
            afterSaltOrderVO.setLogiOrder(xlCustomerAftersale.getLogiCode());
            afterSaltOrderVO.setWoStatus(Integer.valueOf(xlCustomerAftersale.getWoStatus()));
            afterSaltOrderVO.setWorkorder(xlCustomerAftersale.getWorkorder());
            afterSaltOrderVO.setCreateTime(xlCustomerAftersale.getCreateTime());
            targetResult.add(afterSaltOrderVO);
        }
        return targetResult;
    }

    @Override
    public List<AfterSaltOrderVO> getAfterOrderListByToken( String woStatus) {
        //当前操作人
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //当前用户的角色
        String roles = user.getRoleCode();
        String phone = user.getPhone();
        QueryWrapper<XlCustomerMystore> xlCustomerAftersaleQueryWrapper = new QueryWrapper<>();
        xlCustomerAftersaleQueryWrapper.eq("phone",phone);
        List<XlCustomerMystore> mystoreList = xlCustomerMystoreService.list(xlCustomerAftersaleQueryWrapper);
        //获取我的门店清单
        List<String> mystoreStr = mystoreList.stream().map(XlCustomerMystore::getStoreCode).collect(Collectors.toList());
        if(ObjectUtil.isEmpty(mystoreStr)){
            mystoreStr = new ArrayList<>();
            mystoreStr.add("notchargestore");
        }
        QueryWrapper<XlCustomerAftersale> ordeQueryWrapper = new QueryWrapper<>();
        ordeQueryWrapper.in("store_code",mystoreStr);

        ordeQueryWrapper.eq(!woStatus.equals("all"),"wo_status",woStatus);
        List<XlCustomerAftersale> list  = xlCustomerAftersaleMapper.selectList(ordeQueryWrapper);
        List<AfterSaltOrderVO> targetResult = new ArrayList();
        for(XlCustomerAftersale xlCustomerAftersale : list){
            AfterSaltOrderVO afterSaltOrderVO = new AfterSaltOrderVO();
            afterSaltOrderVO.setLogiOrder(xlCustomerAftersale.getLogiCode());
            afterSaltOrderVO.setWoStatus(Integer.valueOf(xlCustomerAftersale.getWoStatus()));
            afterSaltOrderVO.setWorkorder(xlCustomerAftersale.getWorkorder());
            afterSaltOrderVO.setCreateTime(xlCustomerAftersale.getCreateTime());
            afterSaltOrderVO.setStoreCode(xlCustomerAftersale.getStoreCode());
            afterSaltOrderVO.setStoreName(xlCustomerAftersale.getStoreName());
            targetResult.add(afterSaltOrderVO);
        }
        return targetResult;
    }

@Autowired
private IXlCustomerLogisticPackageService logisticPackageService;
    @Override
    public ASOrderVO getAfterOrderDetail(String workorder) {
        ASOrderVO asOrderVO = new ASOrderVO();
        QueryWrapper<XlCustomerAftersale> xlCustomerAftersaleQueryWrapper = new QueryWrapper<>();
        xlCustomerAftersaleQueryWrapper.eq("workorder",workorder);
        XlCustomerAftersale main = xlCustomerAftersaleMapper.selectOne(xlCustomerAftersaleQueryWrapper);

        /**物流单号*/
        asOrderVO.setLogiOrder(main.getLogiCode());

        QueryWrapper<XlCustomerLogisticPackage> xlCustomerLogisticPackageQueryWrapper = new QueryWrapper<>();
        xlCustomerLogisticPackageQueryWrapper.eq("logi_order",main.getLogiCode());
        XlCustomerLogisticPackage logisticPackage = logisticPackageService.list(xlCustomerLogisticPackageQueryWrapper).get(0);
        asOrderVO.setLogiCom(logisticPackage.getLogiCom());
        /**订单单号*/
        asOrderVO.setOrderCode(main.getOrderCode());

        asOrderVO.setStoreCode(main.getStoreCode());

        asOrderVO.setStoreName(main.getStoreName());
        /**售后类型*/
        asOrderVO.setAftersaleType(main.getAftersaleType());
        /**售后原因*/
        asOrderVO.setRenson(main.getRenson());
        /**售后凭证*/
        asOrderVO.setWoImage(main.getWoImage());

        List<ASOrderDetailVo> details =  xlCustomerAftersaleDetailMapper.getAfterOrderDetail(workorder);

        asOrderVO.setAftersaleDetailList(details);
        return asOrderVO;
    }

    @Override
    public List<MyStoreVO> getMyStore() {
        //当前操作人
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //当前用户的角色
        String roles = user.getRoleCode();
        String phone = user.getPhone();
        //先从缓存查
        QueryWrapper<XlCustomerMystore> xlCustomerAftersaleQueryWrapper = new QueryWrapper<>();
        xlCustomerAftersaleQueryWrapper.eq("phone",phone);
        List<XlCustomerMystore> mystoreList = xlCustomerMystoreService.list(xlCustomerAftersaleQueryWrapper);
        if(ObjectUtil.isEmpty(mystoreList)){
            MyStoreVO  notchargeStore = new MyStoreVO();
            notchargeStore.setStoreCode("无负责门店");
            notchargeStore.setStoreName("无负责门店");
            List<MyStoreVO> targetListsss = new ArrayList<>();
            targetListsss.add(notchargeStore);
            return  targetListsss;
        }
        List<String> mystoreStr = mystoreList.stream().map(XlCustomerMystore::getStoreCode).collect(Collectors.toList());

        QueryWrapper<XlCustomerStoreInfo> queryWrapper = new QueryWrapper<>();

        queryWrapper.in("store_code",mystoreStr);

        List<XlCustomerStoreInfo> storeInfos = xlCustomerStoreInfoService.list(queryWrapper);

        List<MyStoreVO> targetList = new ArrayList<>();
        for(XlCustomerStoreInfo xlCustomerMystore : storeInfos){
            MyStoreVO myStoreData = new MyStoreVO();
            myStoreData.setStoreCode(xlCustomerMystore.getStoreCode());
            myStoreData.setStoreName(xlCustomerMystore.getStoreName());
            targetList.add(myStoreData);
        }
        return targetList;
    }

    @Override
    public List<MyStoreDataVO> getMyStoreData() {
        List<MyStoreVO> list = getMyStore();
        //获取门店数据
        List<MyStoreDataVO> targetList = new ArrayList<>();
        if(ObjectUtil.isEmpty(list)){
            MyStoreDataVO myStoreData = new MyStoreDataVO();
            myStoreData.setStoreCode("您没有所辖门店，请联系管理员");
            myStoreData.setStoreName("您没有所辖门店，请联系管理员");
            myStoreData.setTotalAfterSaleAmount(0);
            myStoreData.setTotalNotPaymentAmount(0);
            myStoreData.setTotalPaymentAmount(0);
            myStoreData.setTotalOrderAmount(0);
            targetList.add(myStoreData);
            return targetList;
        }
        String targetStores = list.stream().map(storeVO -> "'" + storeVO.getStoreCode() + "'").collect(Collectors.joining(","));

        List<MyStoreDataVO>  myStoreDataVOS = xlCustomerOrdeService.getMyStoreData(targetStores);

        if(ObjectUtil.isEmpty(myStoreDataVOS)){
            for(MyStoreVO xlCustomerMystore : list){
                MyStoreDataVO myStoreData = new MyStoreDataVO();
                myStoreData.setStoreCode(xlCustomerMystore.getStoreCode());
                myStoreData.setStoreName(xlCustomerMystore.getStoreName());
                myStoreData.setTotalAfterSaleAmount(0);
                myStoreData.setTotalNotPaymentAmount(0);
                myStoreData.setTotalPaymentAmount(0);
                myStoreData.setTotalOrderAmount(0);
                targetList.add(myStoreData);
            }
            return targetList;
        }
        HashSet<String> myStoreDataSet =  new HashSet<>();
        for(MyStoreDataVO myStoreDataVO : myStoreDataVOS){
            myStoreDataSet.add(myStoreDataVO.getStoreCode());
        }
        for(MyStoreVO xlCustomerMystore : list){
            if(myStoreDataSet.contains(xlCustomerMystore.getStoreCode())){
                continue;
            }else{
                MyStoreDataVO myStoreData = new MyStoreDataVO();
                myStoreData.setStoreCode(xlCustomerMystore.getStoreCode());
                myStoreData.setStoreName(xlCustomerMystore.getStoreName());
                myStoreData.setTotalAfterSaleAmount(0);
                myStoreData.setTotalNotPaymentAmount(0);
                myStoreData.setTotalPaymentAmount(0);
                myStoreData.setTotalOrderAmount(0);
                myStoreDataVOS.add(myStoreData);
            }
        }
       return myStoreDataVOS;
    }

    @Override
    public List<OrderVO> getOrderListByToken(String listType) {

        //当前操作人
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //当前用户的角色
        String roles = user.getRoleCode();
        String phone = user.getPhone();
        QueryWrapper<XlCustomerMystore> xlCustomerAftersaleQueryWrapper = new QueryWrapper<>();
        xlCustomerAftersaleQueryWrapper.eq("phone",phone);
        List<XlCustomerMystore> mystoreList = xlCustomerMystoreService.list(xlCustomerAftersaleQueryWrapper);
        //获取我的门店清单
        List<String> mystoreStr = mystoreList.stream().map(XlCustomerMystore::getStoreCode).collect(Collectors.toList());
        if(ObjectUtil.isEmpty(mystoreStr)){
             mystoreStr = new ArrayList<>();
            mystoreStr.add("notchargestore");
        }
        QueryWrapper<XlCustomerOrde> ordeQueryWrapper = new QueryWrapper<>();
        ordeQueryWrapper.in("store_code",mystoreStr);
        //listType=1 预采购订单-未确认 listType=2 预采购订单-已确认 ，listType=3 预采购订单-未支付 ，listType=4 预采购订单-已支付 ，
        if("1".equals(listType)){//预采购订单，只查询为提交的订单
            ordeQueryWrapper.eq("audit_state","-1");
        }
        if("2".equals(listType)){//预采购订单，
            ordeQueryWrapper.ne("audit_state","-1");//不等于-1， 只查询1提交 2已审核
        }
        if("3".equals(listType)){//采购订单-未支付,审核通过且未支付
            ordeQueryWrapper.ne("audit_state","1");//不等于-1， 只查询1提交 2已审核
            ordeQueryWrapper.isNull("payment_state");//状态为空就是未支付
        }
        if("4".equals(listType)){//采购订单-已支付
            ordeQueryWrapper.ne("audit_state","-1");//不等于-1， 只查询1提交 2已审核
            ordeQueryWrapper.eq("payment_state","1");//等于1
        }

        List<XlCustomerOrde> list  = xlCustomerOrdeService.list(ordeQueryWrapper);
        List<OrderVO> targetResult = new ArrayList();
        for(XlCustomerOrde xlCustomerOrde : list){
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(xlCustomerOrde, orderVO);
            targetResult.add(orderVO);
        }
        return targetResult;
    }

    @Override
    public Result<String> deleteAfterSaltOrder(String workorder) {
        QueryWrapper<XlCustomerAftersale> ordeQueryWrapper = new QueryWrapper<>();
        ordeQueryWrapper.eq("workorder",workorder);
        XlCustomerAftersale  xlCustomerAftersale= xlCustomerAftersaleMapper.selectOne(ordeQueryWrapper);
        if(ObjectUtil.isEmpty(xlCustomerAftersale)){
            return Result.error("售后订单不存在，删除失败！");
        }
        //售后单状态（0:待审批，1:审批通过,2:审批不通过）
        if("1".equals(xlCustomerAftersale.getWoStatus())){
            return Result.error("审批过的售后订单不允许删除，删除失败！");
        }
        xlCustomerAftersaleDetailMapper.deleteAfterOrder(workorder);
        xlCustomerAftersaleDetailMapper.deleteAfterOrderDetail(workorder);
        return Result.ok("删除成功！");
    }

    @Override
    public List<OrderDetailVo> getOrderDetail(String ordercode) {

        List<OrderDetailVo> result = new ArrayList<>();
        //查询订单所有的明细
        List<OrderDetailNew> orderDetailNews = xlCustomerOrderDetailService.queryNewOrderDetail(ordercode);

        int sortNo = 1;
        //分组-全部
        OrderDetailVo  allGroup = new OrderDetailVo();
        List<OrderDetailNew> groupList;
        allGroup.setGroupName("全部");
        allGroup.setGroupSize(orderDetailNews.size());
        allGroup.setGroupList(orderDetailNews);
        allGroup.setSortNo(sortNo);
        result.add(allGroup);

        //根据l2级别进行分组
        Map<String, List<OrderDetailNew>> groupedL2Type = orderDetailNews.stream()
                .collect(Collectors.groupingBy(
                        orderDetail -> ObjectUtil.isEmpty(orderDetail.getL2Type())? "其他" : orderDetail.getL2Type()
                ));


        //处理分组结果，每个分组就是一个订单
        for (Map.Entry<String, List<OrderDetailNew>> entry : groupedL2Type.entrySet()) {
            String type = entry.getKey();
            List<OrderDetailNew> typeDetailList = entry.getValue();
            OrderDetailVo tempGroup = new OrderDetailVo();
            tempGroup.setGroupName(type);
            tempGroup.setGroupSize(typeDetailList.size());
            tempGroup.setGroupList(typeDetailList);
            sortNo++;
            tempGroup.setSortNo(sortNo);
            result.add(tempGroup);
        }

        return result;
    }
    @Override
    public List<OrderDetailVo> getOrderDetailNew(String ordercode,String upcCode) {

        List<OrderDetailVo> result = new ArrayList<>();
        //查询订单所有的明细
        List<OrderDetailNew>  orderDetailListTarget = xlCustomerOrderDetailService.queryNewOrderDetail(ordercode);
        List<OrderDetailNew> orderDetailNews = new ArrayList<>();
        if(ObjectUtil.isNotEmpty(upcCode)){
            for(OrderDetailNew orderDetailNew :orderDetailListTarget){
                boolean a = ObjectUtil.isNotEmpty(orderDetailNew.getProductName())&&orderDetailNew.getProductName().contains(upcCode);
                boolean b = ObjectUtil.isNotEmpty(orderDetailNew.getUpcCode())&&orderDetailNew.getUpcCode().contains(upcCode);
                if(a||b){
                    orderDetailNews.add(orderDetailNew);
                }
            }
        }else{
            orderDetailNews.addAll(orderDetailListTarget);
        }

        int sortNo = 1;
        //分组-全部
        OrderDetailVo  allGroup = new OrderDetailVo();
        List<OrderDetailNew> groupList;
        allGroup.setGroupName("全部");
        allGroup.setGroupSize(orderDetailNews.size());
        allGroup.setGroupList(orderDetailNews);
        allGroup.setSortNo(sortNo);
        result.add(allGroup);

        //根据l2级别进行分组
        Map<String, List<OrderDetailNew>> groupedL2Type = orderDetailNews.stream()
                .collect(Collectors.groupingBy(
                        orderDetail -> ObjectUtil.isEmpty(orderDetail.getL2Type())? "其他" : orderDetail.getL2Type()
                ));

        for (Map.Entry<String, List<OrderDetailNew>> entry : groupedL2Type.entrySet()) {
            String type = entry.getKey();
            List<OrderDetailNew> typeDetailList = entry.getValue();
            OrderDetailVo tempGroup = new OrderDetailVo();
            tempGroup.setGroupName(type);
            tempGroup.setGroupSize(typeDetailList.size());
            tempGroup.setGroupList(typeDetailList);
            sortNo++;
            tempGroup.setSortNo(sortNo);
            result.add(tempGroup);
        }

        return result;
    }

    @Override
    public List<MenuDTO> getMenuList() {
        //获取角标数据
        //当前操作人
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //当前用户的角色
        String roles = user.getRoleCode();
        String phone = user.getPhone();
        QueryWrapper<XlCustomerMystore> xlCustomerAftersaleQueryWrapper = new QueryWrapper<>();
        xlCustomerAftersaleQueryWrapper.eq("phone",phone);
        List<XlCustomerMystore> mystoreList = xlCustomerMystoreService.list(xlCustomerAftersaleQueryWrapper);
        //获取我的门店清单
//        List<MyStoreVO> myStoreVOList = getMyStore();
//        String targetStores = myStoreVOList.stream().map(storeVO -> "'" + storeVO.getStoreCode() + "'").collect(Collectors.joining(","));
//        List<CornerNum>  cornerNums = xlCustomerOrderDetailService.getCornerNum(targetStores);
        List<MenuDTO>  result = new ArrayList<>();
        MenuDTO shouhou = new MenuDTO();
        shouhou.setMenuId("shouhouguanli");
        shouhou.setMenuName("售后管理");
        shouhou.setIcon(null);
        shouhou.setSelectedIcon(null);
        shouhou.setCornerNum(12);
        shouhou.setPath("/subPackages/pages/ticket/ticket");
        result.add(shouhou);
        MenuDTO yucaigoudingdan = new MenuDTO();
        yucaigoudingdan.setMenuId("yucaigoudingdan");
        yucaigoudingdan.setMenuName("预采购订单");
        yucaigoudingdan.setIcon(null);
        yucaigoudingdan.setSelectedIcon(null);
        //
        yucaigoudingdan.setCornerNum(12);
        yucaigoudingdan.setPath("/subPackages/pages/purchase-order/purchase-order?type=pre");
        result.add(yucaigoudingdan);
        MenuDTO caigoudingdan = new MenuDTO();
        caigoudingdan.setMenuId("caigoudingdan");
        caigoudingdan.setMenuName("采购管理");
        caigoudingdan.setIcon(null);
        caigoudingdan.setSelectedIcon(null);
        caigoudingdan.setCornerNum(12);
        caigoudingdan.setPath("/subPackages/pages/purchase-order/purchase-order?type=order");
        result.add(caigoudingdan);
        return result;
    }

    @Override
    public List<H5LogiVo> getLogiList(String ordercode) {
        return   xlCustomerLogisticPackageService.getLogiListH5(ordercode);
    }

    @Override
    public Page<OrderVO> getOrderListByPage(String listType, String storeCode, String orderCode, Integer pageNo, Integer pageSize) {
        QueryWrapper<XlCustomerOrde> ordeQueryWrapper = new QueryWrapper<>();
        Page<XlCustomerOrde> page = new Page<>(pageNo,pageSize);
        ordeQueryWrapper.eq("store_code",storeCode);
        ordeQueryWrapper.orderByDesc("create_time");
        ordeQueryWrapper.eq(ObjectUtil.isNotEmpty(orderCode),"order_code",orderCode);

        //listType=all 全部 listType=notpay 未支付 ，listType= notshipment 未发货 ，listType=notreceive  未收货  listType=received 已收货
        if("全部".equals(listType)){//全部订单
            // ordeQueryWrapper.eq("audit_state","-1");
        }
        if("待支付".equals(listType)){//待支付，
            ordeQueryWrapper.eq("order_status","待支付");
        }
        if("待审核".equals(listType)){//待审核，
            ordeQueryWrapper.eq("order_status","待审核");
        }
        if("待发货".equals(listType)){//待发货，
            ordeQueryWrapper.eq("order_status","待发货");
        }
        if("待收货".equals(listType)){//待发货，
            ordeQueryWrapper.eq("order_status","待收货");
        }
        Page<XlCustomerOrde> listPage  = xlCustomerOrdeService.page(page,ordeQueryWrapper);
        Page<OrderVO> targetResult = new Page<>(listPage.getCurrent(),listPage.getSize(),listPage.getTotal());
        List<OrderVO> orderVOS = new ArrayList<>();
        for(XlCustomerOrde xlCustomerOrde : listPage.getRecords()){
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(xlCustomerOrde, orderVO);
            fixStatus(orderVO,xlCustomerOrde);
            orderVO.setDetails( xlCustomerOrderDetailService.queryNewOrderDetail(xlCustomerOrde.getOrderCode()));
            orderVOS.add(orderVO);
        }
        targetResult.setRecords(orderVOS);
        return targetResult;
    }

    @Override
    public Result<String> signatureByQrCode(String orderCode) {
        Result<String> result = new Result<>();
        //司机扫码签收
        QueryWrapper<XlCustomerOrde> ordeQueryWrapper = new QueryWrapper<>();
        ordeQueryWrapper.eq("order_code",orderCode);
        ordeQueryWrapper.eq("order_status","待收货");
        XlCustomerOrde xlCustomerOrde = xlCustomerOrdeService.getOne(ordeQueryWrapper);
        if(ObjectUtil.isEmpty(xlCustomerOrde)){
            return Result.error("扫码失败,原因：订单不存在或订单状态不是待收货");
        }
        UpdateWrapper<XlCustomerOrde> updateWrapper = new UpdateWrapper<>();
        //当前操作人
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        updateWrapper.set("order_status","已收货").set("driver",user.getUsername()).eq("id",xlCustomerOrde.getId());
        xlCustomerOrdeService.update(updateWrapper);
        return Result.ok("扫码签收成功");
    }

    @Override
    public String sftPayNotifyUrl(PayNotifyRequest payNotifyRequest) {
        String orderCode = payNotifyRequest.getOutTradeNo();
        QueryWrapper<XlCustomerOrde> ordeQueryWrapper = new QueryWrapper<>();
        ordeQueryWrapper.eq("order_code",orderCode);
        ordeQueryWrapper.eq("order_status","待支付");
        XlCustomerOrde xlCustomerOrde = xlCustomerOrdeService.getOne(ordeQueryWrapper);
        if(ObjectUtil.isEmpty(xlCustomerOrde)){
            return "SUCCESS";
        }
        //收到盛付通支付回调，更新订单状态
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        UpdateWrapper<XlCustomerOrde> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("order_status","待审核")
                .set("payment_state","1")
                .set("payment_time",new Date())
                .set("payment_by","noifyUrl")
                .set("payment_amount",payNotifyRequest.getTotalFee()/100)
                .eq("id",xlCustomerOrde.getId());
        xlCustomerOrdeService.update(updateWrapper);
        xlLogUtil.insertLog(xlCustomerOrde.getOrderCode(),"支付回调","支付成功回调通知",new Date(),"待支付","待审核");
        return "SUCCESS";
    }

    @Override
    public String sftOrderQuery(String orderCode) throws Exception {
        OrderQueryRequest orderQueryRequest = new OrderQueryRequest(orderCode);
        String sign = ShengFuTongSignUtil.sign(BeanUtil.beanToMap(orderQueryRequest), ShengftConf.PRIVATEKEY);// WalletSignUtils.sign(request, AggreConfig.PRIVATEKEY, SignType.RSA, new String[]{"sign"});
        orderQueryRequest.setSign(sign);
        System.out.println("PreUnifieAppletdorderResponse request : "+ JSON.toJSONString(orderQueryRequest));
        String resultJsonTemp = HttpUtil.post(ShengftConf.URL.concat("/pay/queryOrder"), JSON.toJSONString(orderQueryRequest));
        QueryOrderResponse queryOrderResponse = JSONUtil.toBean(resultJsonTemp, QueryOrderResponse.class);
        System.out.println("PreUnifieAppletdorderResponse response : "+resultJsonTemp);
        return null;
    }


    public Result<String> receiveOrder(String orderCode)  {
        QueryWrapper<XlCustomerOrde> ordeQueryWrapper = new QueryWrapper<>();
        ordeQueryWrapper.eq("order_code",orderCode);
        ordeQueryWrapper.eq("order_status","待收货");
        XlCustomerOrde xlCustomerOrde = xlCustomerOrdeService.getOne(ordeQueryWrapper);
        if(ObjectUtil.isEmpty(xlCustomerOrde)){
            return Result.error("签收,原因：订单不存在或订单状态不是待收货");
        }
        UpdateWrapper<XlCustomerOrde> updateWrapper = new UpdateWrapper<>();
        //当前操作人
        updateWrapper.set("order_status","已收货").eq("id",xlCustomerOrde.getId());
        xlCustomerOrdeService.update(updateWrapper);
        xlLogUtil.insertLog(xlCustomerOrde.getOrderCode(),"收货","小程序用户进行收货",new Date(),"待收货","已收货");
        return Result.ok("收货成功");
    }

    private void fixStatus(OrderVO orderVO,XlCustomerOrde xlCustomerOrde) {
        if("待支付".equals(xlCustomerOrde.getOrderStatus())){//待支付
            orderVO.setOrderActions(Arrays.asList("去支付"));
        }
        if("待审核".equals(xlCustomerOrde.getOrderStatus())){//待审核
            orderVO.setOrderActions(Arrays.asList("申请售后"));
        }
        if("待发货".equals(xlCustomerOrde.getOrderStatus())){//待发货
            if("1".equals(xlCustomerOrde.getIsCity())){//城配订单 出示收货码
                orderVO.setOrderActions(Arrays.asList("查看物流","出示收货码","申请售后"));
            }else{
                orderVO.setOrderActions(Arrays.asList("查看物流","申请售后"));
            }
        }
        if("待收货".equals(xlCustomerOrde.getOrderStatus())){//待收货
            orderVO.setOrderActions(Arrays.asList("查看物流","收货","申请售后"));
        }
        if("已收货".equals(xlCustomerOrde.getOrderStatus())){//待收货
            orderVO.setOrderActions(Arrays.asList("查看物流","申请售后"));
        }
    }


}
